<template>
  <common-layout>
    <a-row class="login" type="flex" justify="center">
      <div class="left">
        <img alt="logo" class="logo" src="@/assets/img/logo.png" />
        <div class="talent">
          敏捷 高效 利他
        </div>
        <div class="kh">
          以推动天下蓝领快乐工作、幸福生活为己任<br />
          成为全球蓝领首选的终身服务平台
        </div>
      </div>
      <div class="right">
        <div class="tips">钉钉扫码后点击“确认授权”，即可完成账号绑定及登录。<br />支持APP扫码登录</div>
        <div id="login_container"></div>
        <div class="help">扫码无法登录？<br />请联系上级主管或HR确认钉钉是否已加入企业。</div>
      </div>
    </a-row>
  </common-layout>
</template>

<script>
import CommonLayout from '@/layouts/CommonLayout'
import { tkLogin } from '@/services/user'
import { setAuthorization } from '@/utils/request'
import { loadRoutes } from '@/utils/routerUtil'
import { mapMutations } from 'vuex'

export default {
  name: 'Login',
  components: { CommonLayout },
  data () {
    return {
      code: "",
      logging: false,
      error: '',
      form: this.$form.createForm(this)
    }
  },
  computed: {
    systemName () {
      return this.$store.state.setting.systemName
    }
  },
  mounted () {
    // code是登录所需最终参数
    const { code } = this.$route.query
    console.log('code', code)
    if (code) { // 登录接口
      this.goWorkPlace(code)
    } else { // 钉钉二维码
      this.ddLoginInit()
    }
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
    ddLoginInit () {
      // 钉钉扫码流程：扫码成功登录后会自动跳到这个url页面，url路径会携带code，你拿到这个code，调用登录接口成功就跳转。
      // 你的项目页面
      let url = encodeURIComponent('http://localhost:8080/#/login');
      // appid 找后端要
      let appid = 'dingoa9pyb9i6fljfan9v8'
      // 钉钉自己的url 修改上面俩，不需要动这个
      let u = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`
      let goto = encodeURIComponent(u)
      let obj = window.DDLogin({
        id: "login_container",// 这里需要你在自己的页面定义一个HTML标签并设置id，例如<div id="login_container"></div>或<span id="login_container"></span>
        goto: goto, // 请参考注释里的方式
        style: "border:none;background-color:#FFFFFF;",
        width: "100%",// 官方参数 365
        height: "300"// 官方参数 400
      });
      console.log(obj)
      let handleMessage = (event) => {
        let origin = event.origin;
        if (origin == "https://login.dingtalk.com") { // 判断是否来自ddLogin扫码事件。
          let loginTmpCode = event.data;
          // 获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
          console.log("loginTmpCode", loginTmpCode);
          // 此步拿到临时loginTmpCode换取正式code
          // window.location.href = `${u}&loginTmpCode=${loginTmpCode}`;
          window.location.replace(`${u}&loginTmpCode=${loginTmpCode}`);
        }
      };
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false);
      } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage);
      }
    },
    goWorkPlace (code) {
      // 获取token
      let prams = {
        channelType: 'PC',
        loginType: 'DING',
        ddScanCode: code
      }
      tkLogin(prams).then(this.afterLogin)
    },
    afterLogin (res) {
      this.logging = false
      const loginRes = res.data
      if (loginRes.code == 200) {
        // const { user, permissions, userRoleList } = loginRes.data
        console.log(loginRes)
        // this.setUser(user)
        // this.setPermissions(permissions)
        // this.setRoles(userRoleList)
        setAuthorization({ token: loginRes.data.token, expireAt: new Date(loginRes.data.expireAt) })
        // 获取路由配置 loginRes.data.authorityList
        loadRoutes([
          {
            "router": "root",
            "children": [
              {
                "router": "workplace",
              },
              {
                "router": "authorityManagement",
                "children": ["roleManagement"]
              },
              {
                "router": "quickEntry",
                "children": ["employeeBatchProcessing"]
              },
              {
                "router": "systemConfig",
                "children": ["contractingSubjectManagement"]
              }
            ]
          }
        ])
        this.$router.replace('/workplace')
        this.$message.success('欢迎回来', 3)
      } else {
        this.$router.replace('/login')
        this.$message.error(loginRes.msg, 6)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.common-layout {
  .login {
    width: 66.66%;
    background: #ffffff;
    box-shadow: 0px 6px 20px 0px rgba(59, 115, 248, 0.1);
    border-radius: 16px;
    overflow: hidden;
    margin: 0 auto;
    box-sizing: border-box;
  }
  .left {
    width: 50%;
    padding: 3.6%;
    background-color: #3370ff;
    color: #ffffff;
    .logo {
      height: 5.7vh;
    }
    .talent {
      font-family: FZLTZHK--GBK1-0, FZLTZHK--GBK1;
      font-size: 54px;
      letter-spacing: 1px;
      padding: 26% 0 36% 0;
    }
    .kh {
      font-size: 16px;
      font-family: Helvetica;
    }
  }
  .right {
    width: 50%;
    padding: 5% 0;
    background-color: #fff;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    .tips,
    .help {
      padding: 0 5%;
      text-align: center;
    }
    .tips {
      color: #222222;
      font-weight: bold;
    }
    .help {
      color: #888888;
    }
  }
}
</style>
